package com.jintoufs.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jintoufs.domain.baseinfo.Customer;
import com.jintoufs.service.baseinfo.CustomerService;
import com.jintoufs.service.user.PasswordHelper;
import com.jintoufs.util.SecretKeyUtils;
import com.jintoufs.util.http.HttpUtils;
import com.jintoufs.util.weixin.AesCbcUtil;
import com.jintoufs.util.weixin.WeixinMessagePush;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yh on 2015/6/16.
 */
@Controller
@Scope("prototype")
@RequestMapping("/customer")
public class CustomerAction extends SupportAction {
    private Log logger = LogFactory.getLog(CustomerAction.class);
    @Resource
    private CustomerService customerService;
    @Autowired
    private PasswordHelper passwordHelper;
    @Autowired
    private WeixinMessagePush weixinMessagePush;

    @Value("${appId}")
    private String APPID;

    @Value("${secret}")
    private String SECRET = "";

    @RequestMapping("/login")
    @ResponseBody
    public AjaxMsg login(HttpServletRequest request, String code, String phone, String password, String encryptedData, String iv) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap<>();
        if (phone != null && password != null && !phone.isEmpty() && !password.isEmpty()) {
            params.put("mobilePhone", phone);
            Customer customer;
            List<Customer> userList = customerService.queryByParams(params);
            if (userList != null && userList.size() > 0) {
                customer = userList.get(0);
                String oriPassword = customer.getPassword();
                customer.setPassword(password);
                String encryptPassword = passwordHelper.encryptPasswordOnly(customer);
                if (encryptPassword.equals(oriPassword)) {
                    ajaxMsg.setCode(AjaxMsg.SUCCESS);
                    //重新生成keyStr
                    String keyStr = SecretKeyUtils.getAppKeyStr();
                    customer.setPassword(encryptPassword);
                    //设置session
                    String url = "https://api.com.jintoufs.service.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
                    String json = HttpUtils.getURLContent(url);
                    HttpSession session = request.getSession();

                    if (!json.isEmpty()) {
                        JSONObject jsonObject = JSON.parseObject(json);
                        String sessionKey = jsonObject.getString("session_key");
                        try {
                            System.out.println("encryptedData:" + encryptedData);
                            System.out.println("iv:" + iv);
                            String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
                            if (null != result && result.length() > 0) {
                                JSONObject userInfoJSON = JSON.parseObject(result);
                                String openId = userInfoJSON.get("openId").toString();
                                String unionId = userInfoJSON.get("unionId").toString();
                                System.out.print("result:" + result);

                                Map<String, Object> map = new HashMap<>();
                                map.put("unionId", unionId);
                                List<Customer> users = customerService.queryByParams(map);
                                if (users != null && !users.isEmpty()) {
                                    customer.setOpenServiceId(users.get(0).getOpenServiceId());
                                    customerService.delete(users.get(0).getId());
                                }
                                customer.setOpenId(openId);
                                customer.setKey(keyStr);
                                customerService.update(customer);
                                session.setAttribute(keyStr, openId + sessionKey);
                                ajaxMsg.setDatas(customer);
                                ajaxMsg.setCode(AjaxMsg.SUCCESS);
                            } else {
                                ajaxMsg.setCode(AjaxMsg.FAILURE);
                                ajaxMsg.setMessage("微信登陆失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage("用户名或密码错误");
                }
            } else {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("用户名或密码错误");
            }
        } else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("用户名或者密码不能为空！");
        }
        return ajaxMsg;
    }
}
